package controller

import (
	"blog/dao"
	"encoding/json"
	"fmt"
	"github.com/julienschmidt/httprouter"
	"html/template"
	"net/http"
	"strconv"
)

//搜索
func SearchHandle(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	dao.CommonAction(r, w)
	//页号
	pageId, err := strconv.ParseInt(r.URL.Query().Get("page"), 10, 64)
	if err != nil {
		pageId = 1
	}
	if pageId < 1 {
		pageId = 1
	}
	//每一页数据条数
	PageSize := int64(20)
	//关键字
	keyWord := func() string {
		param1 := ps.ByName("keyWord")
		if param1 != "" {
			return param1
		}
		param2 := r.URL.Query().Get("keyWord")
		return param2
	}()
	//分类
	typeId := func() int64 {
		param1, _ := strconv.ParseInt(ps.ByName("type"), 10, 64)
		if param1 != 0 {
			return param1
		}
		param2, _ := strconv.ParseInt(r.URL.Query().Get("type"), 10, 64)
		return param2
	}()
	//标签
	tagName := func() string {
		param1 := ps.ByName("tagName")
		if param1 != "" {
			return param1
		}
		param2 := r.URL.Query().Get("tagName")
		return param2
	}()

	t, err := template.New("search.html").Funcs(dao.FuncMap).ParseFiles("templates/search.html", "templates/pub_inc.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	/*
	   url = "/search?page="+destPage;
	   if(keyWord)
	       url+= "&keyWord="+keyWord;
	   if(typeId)
	       url+= "&type="+typeId;
	   if(TagName)
	       url+= "&tagName="+TagName;
	*/

	baseUrl := "/search?"
	if keyWord != "" {
		baseUrl += fmt.Sprintf("&keyWord=%s", keyWord)
	}
	if typeId != 0 {
		baseUrl += fmt.Sprintf("&type=%d", typeId)
	}
	if tagName != "" {
		baseUrl += fmt.Sprintf("&tagName=%s", tagName)
	}

	d := struct {
		KeyWord       string
		ResultList    dao.PostListData
		Page          int
		TypeId        int64
		TypesInfoJson template.HTML
		TypeListJson  template.HTML
		TagName       string
		BaseUrl       string
	}{
		KeyWord:    keyWord,
		TagName:    tagName,
		ResultList: dao.GetPostListByKeyWord(keyWord, tagName, typeId, pageId, PageSize, false),
		Page:       int(pageId),
		TypeId:     typeId,
		TypesInfoJson: func() template.HTML {
			bytes, _ := json.Marshal(dao.GetPostTypeInfo(int(typeId)))
			return template.HTML(string(bytes))
		}(),
		TypeListJson: func() template.HTML {
			bytes, _ := json.Marshal(dao.GetTypeList(0, 1))
			return template.HTML(string(bytes))
		}(),
		BaseUrl: baseUrl,
	}

	t.Execute(w, d)
}
